import cv2 as cv
import numpy as np

filename = r'vtest.avi'

capvideo = cv.VideoCapture(filename)
fgbg = cv.createBackgroundSubtractorMOG2()
thresh = 200

while True:
    ret,frame = capvideo.read()
    if not ret: #没有新帧，退出
        break
    fgmask = fgbg.apply(frame)
    #noise reduction
    _,fgmask = cv.threshold(fgmask,30,0xff,cv.THRESH_BINARY)
    bgImage = fgbg.getBackgroundImage()
    '''
    findContours函数实际上返回了三个值:
    第一个，返回了你所处理的图像
    第二个，轮廓的点集
    第三个，各层轮廓的索引
    '''
    cnts = cv.findContours(fgmask.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)[1]
    count = 0
    for c in cnts:
        area = cv.contourArea(c)
        if area<thresh:
            continue
        count += 1

        (x, y, w, h) = cv.boundingRect(c)
        cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        print('( %d, %d, %d, %d )'%(x,y,w,h))

    print('共检测到', count, '个目标', '\n')

    cv.imshow("bkImage",bgImage)
    cv.imshow("fgmask",fgmask)

    key = cv.waitKey(30)
    if key == 27 :
        break




cv.waitKey()
cv.destroyAllWindows()